// pages/add/main.js
const dataInit = () => ({
  name: "",
  age: "",
  skill: "",
  gender: "",
  avatar: ""
})
Page({
  /** * 页面的初始数据 */
  data: {
    heroInfo: dataInit()
  },
  async submitForm(event){
    // 获取表单数据
    const { value } = event.detail;
    // 对象合并
    const  heroInfo  = { ...this.data.heroInfo, ...value};
    // console.log('heroInfo',heroInfo);
    // 空提示处理
    const formTips = ['名称', '年龄', '技能', '性别', '图片'];
    const index = Object.values(heroInfo).findIndex(item=>item.trim() === '');
    if(index !== -1){
      const title = `英雄${formTips[index]}不能为空`
      wx.showToast({ title, icon: 'none' })
      return;
    }
    // 上传图片
    try {
      // 截取图片名字，用于云文件上传
      const filePath = heroInfo.avatar;
      const cloudPath = filePath.split('.').slice(-2).join('.').replace('wxfile://','')
      wx.showLoading({ title: '请等待' })
      console.log('cloudPath',cloudPath);
      console.log('cloudPath',cloudPath);
      
      // 上传图片到云存储
      const { fileID: avatar } = await wx.cloud.uploadFile({ filePath, cloudPath })
      // 更新云数据库图片路径
      await getApp().hero.add({
        data:{ ...heroInfo, avatar, createTime: Date.now() }
      })
      await wx.showToast({ title: '新增英雄成功' })
      wx.switchTab({ url: '/pages/index/main' })
      this.setData({ heroInfo: dataInit() })
    } catch (error) {
      console.log(error);
      wx.showToast({ title: '出现错误', icon: 'none' })
    }
  },
  async uploadAvatar(){
    try {
      // 上传一张图片
      const { tempFiles } = await wx.chooseImage({ count: 1 })
      // console.log('tempFiles', tempFiles)
      // 获取图片路径
      const filePath =  tempFiles[0].path
      // 更新页面信息
      const { heroInfo } = this.data
      heroInfo.avatar = filePath
      this.setData({ heroInfo })
    } catch (error) {
      wx.showToast({ title: '出现错误', icon: 'none' })
    }
  }
})